package org.itzheng.myrxframe.realize.apk;

import android.app.usage.StorageStatsManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.UserHandle;
import android.os.storage.StorageManager;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import android.view.MenuItem;

import org.itzheng.and.baseutils.common.ArrayUtils;
import org.itzheng.and.baseutils.ui.UIUtils;
import org.itzheng.myrxframe.R;
import org.itzheng.myrxframe.base.BaseActivity;
import org.itzheng.myrxframe.http.rxjava.RxHelper;
import org.itzheng.myrxframe.realize.apk.receiver.PackageReceiver;
import org.itzheng.myrxframe.utils.MenuUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.functions.Consumer;

/**
 * Title:Apk列表<br>
 * Description: <br>
 *
 * @email ItZheng@ZoHo.com
 * Created by itzheng on 2019-4-15.
 */
public class ApkListActivity extends BaseActivity {
    @BindView(R.id.tblTop)
    TabLayout tblTop;
    @BindView(R.id.vpContent)
    ViewPager vpContent;
    private List<ApkListFragment> mFragments = getFragments();

    private List<ApkListFragment> getFragments() {
        List<ApkListFragment> list = new ArrayList<>();
        list.add(ApkListFragment.newInstance(ApkListFragment.Type.ALL));
        list.add(ApkListFragment.newInstance(ApkListFragment.Type.USER));
        list.add(ApkListFragment.newInstance(ApkListFragment.Type.SYSTEM));
        return list;
    }

    @Override

    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_apk_list);
        ButterKnife.bind(this);
        setTitle(getString(R.string.title_app_manager));
        showBack(true);
        initTabLayout();
        initFragment();
        checkPermission();
        registerAppReceiver();

    }

    PackageReceiver packageReceiver;

    public enum Model {
        /**
         * 正常情况下
         */
        NORMAL,
        /**
         * 备份模式下
         */
        BACKUP
    }

    /**
     * 当前模式，默认正常模式
     */
    Model currentModel = Model.NORMAL;

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        switch (currentModel) {
            case NORMAL:
                MenuItem backup = MenuUtils.createMenuBackup(menu);
                backup.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
                    @Override
                    public boolean onMenuItemClick(MenuItem item) {
                        currentModel = Model.BACKUP;
                        changeModel();
                        return false;
                    }
                });
                break;
            case BACKUP:
                MenuItem cancel = MenuUtils.createMenuCancel(menu);
                cancel.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
                    @Override
                    public boolean onMenuItemClick(MenuItem item) {
                        currentModel = Model.NORMAL;
                        changeModel();
                        return false;
                    }
                });
                break;
        }

        return super.onCreateOptionsMenu(menu);
    }

    private void changeModel() {
        //先改菜单按钮
        invalidateOptionsMenu();
        for (ApkListFragment f : mFragments) {
            switch (currentModel) {
                case NORMAL:
                    f.setModel(Model.NORMAL);
                    break;
                case BACKUP:
                    f.setModel(Model.BACKUP);
                    break;
            }
        }
    }

    private void registerAppReceiver() {
        packageReceiver = PackageReceiver.register(this).setOnPackageChangeListener(new PackageReceiver.OnPackageChangeListener() {
            @Override
            public void onPackageChange(PackageReceiver.ChangeType changeType, String pkgName) {
                for (ApkListFragment fragment : mFragments) {
                    switch (changeType) {
                        case ADDED:
                            fragment.addApp(pkgName);
                            break;
                        case REMOVED:
                            fragment.removeApp(pkgName);
                            break;

                    }
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        packageReceiver = PackageReceiver.unregister(this, packageReceiver);
    }

    private static final String TAG = "ApkListActivity";

    private void checkPermission() {
        Observable.create(new ObservableOnSubscribe<Boolean>() {
            @Override
            public void subscribe(ObservableEmitter<Boolean> oe) throws Exception {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    StorageStatsManager statsManager = (StorageStatsManager) UIUtils.getContext().getSystemService(Context.STORAGE_STATS_SERVICE);
                    UserHandle handler = null;
                    handler = UserHandle.getUserHandleForUid(-2);
                    try {
                        //一般系统都有这个吧
                        String packageName = "com.android.systemui";
                        statsManager.queryStatsForPackage(StorageManager.UUID_DEFAULT, packageName, handler);
                    } catch (PackageManager.NameNotFoundException e) {
                        e.printStackTrace();
                    } catch (SecurityException e) { //这里说明没有权限，没有权限只能查询自身应用大小
                        e.printStackTrace();
                        //这里是缺少权限
                        oe.onNext(true);
                    }
                }
                oe.onComplete();
            }
        }).compose(RxHelper.observableIO2Main()).subscribe(new Consumer<Boolean>() {
            @Override
            public void accept(Boolean aBoolean) throws Exception {
                if (aBoolean) {
                    //如果缺少权限就进行获取
                    Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
                    startActivity(intent);
                }
            }
        });

    }

    private void initTabLayout() {
        tblTop.setupWithViewPager(vpContent);
    }

    private void initFragment() {
        vpContent.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public int getCount() {
                return ArrayUtils.size(mFragments);
            }

            @Override
            public Fragment getItem(int position) {
                return mFragments.get(position);
            }

            @Override
            public CharSequence getPageTitle(int position) {
                return mFragments.get(position).getTitle();
            }
        });
    }
}
